package cn.ctodb.commons.file.client;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;

import cn.ctodb.commons.file.Constants;

public class LocalClient extends ObjectStorage {

	private String dir;

	@Override
	protected void init() {
		super.init();
		dir = properties.getProperty(Constants.DIR);
	}

	public static Logger logger = LoggerFactory.getLogger(LocalClient.class);

	@Override
	public byte[] load(String fileid) throws IOException {
		File file = new File(fileid);
		try {
			return FileCopyUtils.copyToByteArray(file);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		return null;
	}

	@Override
	public void delete(String fileid) throws IOException {
		if (null == fileid)
			throw new IOException("LocalClient invalid arguement");
		File file = new File(fileid);
		if (file.exists()) {
			file.delete();
		}
	}

	@Override
	public String save(byte[] bytes, String extName) throws IOException {
		String fileName = dir + File.separator + UUID.randomUUID() + "." + extName;
		File file = new File(fileName);
		FileCopyUtils.copy(bytes, file);
		return fileName;
	}
}
